package station.Bluetooth;

import java.io.DataInputStream;

import javax.swing.SwingUtilities;

import station.GUI.MainForm;


public class NXTListingThread extends Thread {
//
	private boolean shoudStop;
	private MainForm mainForm;
	private DataInputStream _NXTInputStream;

	public NXTListingThread() {
		super("listingThread");
	}

	@Override
	public void run() {
		if (_NXTInputStream == null) {
			System.out.println("No input stream from device found!");
			return;
		}
		while (!shoudStop) {
			try {
				if(_NXTInputStream != null){
					byte[] buffer = new byte[20];
					if (_NXTInputStream.read(buffer) >= 20) {
						String[] s = getNXTInformations(buffer);
						updateNXTInformations(s);
					}
				}
			} catch (Exception e) {
				//e.printStackTrace();
				System.out.println("Error in runnable ListingThread");
			}
		}
	}

	private String[] getNXTInformations(byte[] buffer) {
		// TODO: optimieren
		String[] info = new String[5];
		
		byte[] battery = new byte[4];
		for (int x = 0; x < 4; x++) {
			battery[x] = buffer[x];
		}
		float akku = (float)(byteToInt(battery)) / 1000;
		info[0] = "" + akku;
		
		byte[] speed = new byte[4];
		for (int x = 4; x < 8; x++) {
			speed[x - 4] = buffer[x];
		}
		info[1] = "" + (float)(byteToInt(speed)) / 10;
		
		byte[] distance = new byte[4];
		for (int x = 8; x < 12; x++) {
			distance[x - 8] = buffer[x];
		}
		info[2] = "" + byteToInt(distance);
		
		byte[] light = new byte[4];
		for (int x = 12; x < 16; x++) {
			light[x - 12] = buffer[x];
		}
		info[3] = "" + byteToInt(light);
		
		byte[] signal = new byte[4];
		for (int x = 16; x < 20; x++) {
			signal[x - 16] = buffer[x];
		}
		info[4] = "" + byteToInt(signal);

		return info;
	}

	private int byteToInt(byte[] b) {
		int number = 0;
		for (int i = 0; i < 4; ++i) {
			number |= (b[3 - i] & 0xff) << (i << 3);
		}
		return number;
	}

	private void updateNXTInformations(final String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
				setStatusText(args);
				}
		});
	}

	public void setShoudStop() {
		shoudStop = true;
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				setStatusText(new String[]{"-----","-----","-----","0","0"});
			}
		});
	}

	public void setMainForm(MainForm mainForm) {
		this.mainForm = mainForm;
	}

	public void setNXTInputStream(DataInputStream dataInputStream) {
		this._NXTInputStream = dataInputStream;
	}
	
	public void setStatusText(String[] args){
		mainForm.lblBatteryvar.setText(args[0]);
		mainForm.lblSpeedvar.setText(args[1]);
		mainForm.lblDistancevar.setText(args[2]);
		mainForm.sliderLightIntensity.setValue(Integer.parseInt(args[3]));
		mainForm.sliderSignalStrenght.setValue(Integer.parseInt(args[4]));
	}
}
